import re

from flask import current_app, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for

from info import db
from info.models import Cases, Comment
from info.modules.case import case_blu


# 品案例
@case_blu.route('/case')
def case():
    """案例列表"""
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 分页查询案例
    current_page = 1
    total_page = 1
    try:
        paginate = Cases.query.paginate(p, 9, False)
        # 获取当前页数据
        case_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    case_list = []
    for case in case_li:
        case_list.append(case.to_case_dict())

    data = {
        'cases': case_list,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template('case.html', data=data)


@case_blu.route('/case_detail/<int:case_id>')
def case_detail(case_id):

    comments = []
    try:
        comments = Comment.query.all()
    except Exception as e:
        current_app.logger.error(e)
    comment_list = []
    for comment in comments:
        comment_list.append(comment.to_dict())

    data = {
        'comments': comment_list,
        'case_id': case_id
    }

    return render_template('case_detail.html', data=data)


@case_blu.route('/case_detail/comment', methods=['POST'])
def comment():
    # 获取参数
    data_dict = request.form
    case_id = data_dict.get("case_id")
    nick_name = data_dict.get("name")
    mobile = data_dict.get("mobile")
    content = data_dict.get("content")
    if not all([case_id, nick_name, mobile, content]):
        return jsonify("参数错误")

    if not re.match("^1[3578][0-9]{9}$", mobile):
        # 提示手机号不正确
        return jsonify("手机号不正确")

    try:
        case = Cases.query.get(case_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify("查询数据失败")

    if not case:
        return jsonify("该案例不存在")

    # 初始化模型，保存数据
    comment = Comment()
    comment.cases_id = case_id
    comment.nick_name = nick_name
    comment.content = content
    comment.mobile = mobile

    # 保存到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify("保存评论数据失败")

    # 返回响应
    return redirect('/case_detail/' + case_id)





